#!/bin/bash

set -eu # be strict

# constants and variables
#
readonly WORKSPACE='workspace'
readonly DEBIAN=( 'control' 'postinst' 'postrm' 'conffiles' 'on.magenta' 'off.magenta' )
readonly DIRLIST=( "$WORKSPACE/DEBIAN" "$WORKSPACE/etc/init.d" "$WORKSPACE/etc/network" "$WORKSPACE/usr/sbin" "$WORKSPACE/usr/share/man/man8" "$WORKSPACE/usr/share/doc/magenta/examples" "$WORKSPACE/usr/share/mc/syntax" )
declare -- VERSION FNAME

# Functions
#
function Die () {
	echo "FAIL: $@." > /dev/stderr
	exit 255
}

# Let's get dangerous!
#
# Some checks first
#
(( EUID )) && Die 'please run me as root'
for FNAME in "${DEBIAN[@]}"; do
	[[ -f "$FNAME" ]] || Die "can't find a required file [$FNAME]"
done

# Allocate our temporary space and populate it
#
[[ -e "$WORKSPACE" ]] && Die "workspace [$WORKSPACE] exists, please remove it or change my constant"
mkdir --parents "${DIRLIST[@]}"
cp "${DEBIAN[@]}" "$WORKSPACE/DEBIAN/"
mv "$WORKSPACE/DEBIAN/on.magenta" "$WORKSPACE/etc/network"
mv "$WORKSPACE/DEBIAN/off.magenta" "$WORKSPACE/etc/network"
cp '../sbin/magenta' "$WORKSPACE/usr/sbin/"
cp '../init.d/magenta' "$WORKSPACE/etc/init.d/"
cp '../man8/magenta.8' "$WORKSPACE/usr/share/man/man8/"
gzip "$WORKSPACE/usr/share/man/man8/magenta.8" || true
cp '../mcedit/magenta.syntax' "$WORKSPACE/usr/share/mc/syntax/"
cp '../doc/examples/on.magenta' "$WORKSPACE/usr/share/doc/magenta/examples/"
cp '../doc/examples/off.magenta' "$WORKSPACE/usr/share/doc/magenta/examples/"
cp --dereference '../doc/README' "$WORKSPACE/usr/share/doc/magenta/"
chown -R root:root "$WORKSPACE"

# Stamp the version
#
read VERSION VERSION VERSION < <("$WORKSPACE/usr/sbin/magenta" --version)
sed -i "s/%VERSION%/$VERSION/" "$WORKSPACE/DEBIAN/control"

# Okay, let's build it
#
dpkg-deb --build "$WORKSPACE" "magenta-$VERSION.deb"

# Clean
#
rm -rf "$WORKSPACE"

exit 0
